package com.aiserver.interceptor;

import com.aiserver.util.JwtUtil;
import com.aiserver.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 * 验证请求中的JWT token
 */
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationInterceptor.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // OPTIONS请求直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        String token = extractToken(request);
        
        if (!StringUtils.hasText(token)) {
            logger.warn("请求缺少token: {}", request.getRequestURI());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未授权访问\",\"timestamp\":" + System.currentTimeMillis() + "}");
            return false;
        }

        // 验证token格式
        if (!jwtUtil.isValidToken(token)) {
            logger.warn("无效的token格式: {}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token格式无效\",\"timestamp\":" + System.currentTimeMillis() + "}");
            return false;
        }

        // 检查token是否过期
        if (jwtUtil.isTokenExpired(token)) {
            logger.warn("token已过期: {}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token已过期\",\"timestamp\":" + System.currentTimeMillis() + "}");
            return false;
        }

        // 检查token是否在黑名单中
        if (redisUtil.isTokenInBlacklist(token)) {
            logger.warn("token已被注销: {}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token已失效\",\"timestamp\":" + System.currentTimeMillis() + "}");
            return false;
        }

        // 验证token类型
        String tokenType = jwtUtil.getTokenType(token);
        if (!"access".equals(tokenType)) {
            logger.warn("token类型错误: {}", tokenType);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token类型错误\",\"timestamp\":" + System.currentTimeMillis() + "}");
            return false;
        }

        // 将用户信息存储到请求属性中
        try {
            Long userId = jwtUtil.getUserIdFromToken(token);
            String username = jwtUtil.getUsernameFromToken(token);
            
            request.setAttribute("userId", userId);
            request.setAttribute("username", username);
            request.setAttribute("token", token);
            
            logger.debug("用户认证成功: userId={}, username={}", userId, username);
            return true;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token解析失败\",\"timestamp\":" + System.currentTimeMillis() + "}");
            return false;
        }
    }

    /**
     * 从请求中提取token
     */
    private String extractToken(HttpServletRequest request) {
        // 从Authorization header中获取
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        
        // 从请求参数中获取
        String paramToken = request.getParameter("token");
        if (StringUtils.hasText(paramToken)) {
            return paramToken;
        }
        
        return null;
    }
}